﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Common;

namespace HanGu.CRM.Areas.Users.Controllers
{
    public class DefaultController : AdminBaseController
    {
        public ActionResult Index()
        {
            SearchParma.IntObj2 = 10;
            return View(GetManagers());
        }

        List<HanGu.Entity.Manager> GetManagers()
        {

            List<HanGu.Entity.Manager> managerList = servicesManager.GetAll(base.SearchParma);
            ViewData["RowCount"] = SearchParma.Pagination.RowCount;
            InitDDL();
            return managerList;
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection)
        {
            SearchParma.Ttile = Request["Title1"];
            return View(GetManagers());
        }
        //
        // GET: /Manager/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Manager/Create
        void InitDDL(int? RoleID = null, int? Status = null)
        {
            ViewData["Roles"] = new SelectList(serviceRoles.GetAll(), "ID", "Name", RoleID);
            ViewData["Parents"] = servicesManager.GetAll();
            ViewData["UserStatus"] = new SelectList(serviceDictionary.GetByGroupName("UserStatus"), "Key", "Value", Status);
            ViewData["Sexs"] = new SelectList(serviceDictionary.GetByGroupName("sex"), "Key", "Value", Status);

        }

        public ActionResult MoveMember(int id = 0)
        {
            ViewData["Parents"] = new SelectList(GetManagersByLevel(false), "ID", "User", id);
            ViewData["SourceID"] = id;
            ViewData["SexList"] = GetListFromDict("sex", true);
            ViewData["MemberGrade"] = GetListFromDict("MemberGrade", true);
            ViewData["Degree"] = GetListFromDict("Degree", true);
            ViewData["Members"] = serviceMemberInfo.GetAllByAssignedIn(id);
            return View();
        }

        [HttpPost]
        public ActionResult MoveMemberRedirect(int id = 0)
        {
            return RedirectToAction("MoveMember", new { id = id });
        }

        [HttpPost]
        public string MoveMember(FormCollection collection)
        {
            try
            {
                string navID = Request["navID"];
                if (!string.IsNullOrEmpty(navID))
                {
                    navTabId = navID;
                }
                int sourceID = 0;
                int.TryParse(Request["SourceID"], out sourceID);
                int? toSourceID = null;
                if (sourceID != 0)
                {
                    toSourceID = sourceID;//转移选择的用户 
                }
                else
                {
                    toSourceID = CurentUser.CurrentUserInfo.ID;//转移当前的用户
                }
                string selectedMembers = Request["moveMembers"];
                string assignedIns = Request["AssignedIns"];
                if (!string.IsNullOrEmpty(selectedMembers))
                {
                    if (servicesManager.MoveMember(selectedMembers, assignedIns, toSourceID))
                    {
                        ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");
                    }
                    else
                    { ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", ""); }
                }
                else
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.MoveMembersNoSelected, navTabId, "", "");
                }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }

        public ActionResult Create(int id = 0)
        {
            HanGu.Entity.Manager manager = null;
            if (id != 0)
            {
                manager = servicesManager.GetByID(id);
            }
            manager = manager ?? new HanGu.Entity.Manager()
            {
                CreateTime = DateTime.Now,
                Creator = CurentUser.UserName
            };
            manager.IsDirectly = manager.IsDirectly ?? false;
            InitDDL(manager.RoleID, manager.Status);
            return View(manager);
        }

        //
        // POST: /Manager/Create
        [HttpPost]
        public string UserExitsed(FormCollection collection)
        {
            string userName = Request["User"];
            var tempManager = servicesManager.GetByUser(userName);
            if (tempManager != null || Common.Helper.SuperUsers.Contains(userName))
            {
                return "false";
            }
            return "true";
        }
        [HttpPost]
        public string Create(FormCollection collection)
        {
            try
            {
                HanGu.Entity.Manager model = new HanGu.Entity.Manager();
                TryUpdateModel(model, collection);
                model.Parent = Request["Parents"];

                var tempManager = servicesManager.GetByUser(model.User);
                if ((model.ID == 0 && tempManager != null) || (model.ID == 0 && Common.Helper.SuperUsers.Contains(model.User)))
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UserExitsed, navTabId, "", "");
                    return "{" + ajaxStr + "}";
                }
                if (Common.Helper.SuperUsers.Contains(model.User) && !string.IsNullOrEmpty(model.Parent))
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UserAdminNoassin, navTabId, "", "");
                    return "{" + ajaxStr + "}";
                }
                if (Common.Helper.SuperUsers.Contains(model.User) && model.Status != 10)
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.UserAdminNoWorkin, navTabId, "", "");
                    return "{" + ajaxStr + "}";
                }
                model.Creator = CurentUser.UserName;
                model.CreateTime = DateTime.Now;
                if (model.Status == 0)
                {
                    var members = serviceMemberInfo.GetAllByAssignedIn(model.ID);
                    if (members != null && members.Count > 0)
                    {
                        ajaxStr = string.Format(ajaxStr, 300, ResourceManager.MoveMembersTip, navTabId, "/Users/Default/MoveMemberRedirect/" + model.ID, "forward");
                        return "{" + ajaxStr + "}";
                    }
                }
                //if (ModelState.IsValid)
                {
                    if (model.ID > 0)
                    {
                        if (Request["setpwd"] != null)//重设密码
                        {
                            string pwd = model.Pwd;
                            model = servicesManager.GetByID(model.ID);
                            model.Pwd = Helper.MD5(pwd);
                        }
                        servicesManager.Update(model);

                        if (CurentUser.SubManager != null)//更新缓存的用户
                        {
                            var managerSub = CurentUser.SubManager.FirstOrDefault(c => c.ID == model.ID);
                            if (managerSub != null)
                            {
                                CurentUser.SubManager.Remove(managerSub);
                                CurentUser.SubManager.Add(model);
                            }
                        }
                    }
                    else
                    {
                        model.Status = 10;
                        model.Pwd = Helper.MD5(model.Pwd);
                        servicesManager.Add(model);
                    }
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.SaveSuccess, navTabId, "", "closeCurrent");

                }
                //else
                //{ ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", ""); ; }
            }
            catch (Exception ex)
            {
                base.ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.SaveFail, navTabId, "", "");
            }
            return "{" + ajaxStr + "}";
        }

        public ActionResult ReSetStatus(int id)
        {
            HanGu.Entity.Manager manager = new HanGu.Entity.Manager();
            if (id != 0)
            {
                manager = servicesManager.GetByID(id);
            }
            return View(manager);
        }
        //
        // GET: /Manager/Edit/5

        public ActionResult ReSetPwd(int id)
        {
            HanGu.Entity.Manager manager = new HanGu.Entity.Manager();
            if (id != 0)
            {
                manager = servicesManager.GetByID(id);
            }
            return View(manager);
        }


        //
        // POST: /Manager/Edit/5

        [HttpPost]
        public ActionResult ReSetPwd(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Manager/Delete/5

        [HttpGet]
        public string Delete(int id)
        {
            try
            {
                servicesManager.Delete(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";
        }


        //
        // POST: /Manager/Delete/5

        [HttpPost]
        public string Delete(int id, FormCollection collection)
        {
            try
            {
                var members = serviceMemberInfo.GetAllByAssignedIn(id);
                if (members != null && members.Count > 0)
                {
                    ajaxStr = string.Format(ajaxStr, 200, ResourceManager.MoveMembersForDelTip, navTabId, "/Users/Default/MoveMemberRedirect/" + id, "forward");
                    return "{" + ajaxStr + "}";
                }

                servicesManager.Delete(id);
                ajaxStr = string.Format(ajaxStr, 200, ResourceManager.DeleteSuccess, navTabId, "", "");
            }
            catch (Exception ex)
            {
                ExceptionHand(ex);
                ajaxStr = string.Format(ajaxStr, 300, ResourceManager.DeleteFail, navTabId, "", "");
            }

            return "{" + ajaxStr + "}";
        }
    }
}
